package com.bwie.service.impl;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbMenuMapper;
import com.bwie.mapper.TbRoleMapper;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbRole;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.UserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author 牛y
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-18 14:16:49
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{


    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    TbMenuMapper tbMenuMapper;

    @Autowired
    TbRoleMapper tbRoleMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    public R sendCode(String mobile) {

        String code = RandomUtil.randomNumbers(6);

        String key="send-"+mobile;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);

        MobileMessageUtil.sendMobileMessage(mobile,code);
        return R.OK();
    }

    @Override
    public R login(UserVo userVo) {

        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, userVo.getUserMobile()));
        if(tbUser==null){
            return R.ERROR(500,"用户为空");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(userVo.getUserPass(), tbUser.getUserPass());
        if(!matches){
            return R.ERROR(500,"密码错误");
        }
        String key="send-"+userVo.getUserMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if(redisCode==null){
            return R.ERROR(500,"验证码已过期");
        }
        if(!redisCode.equals(userVo.getCode())){
            return R.ERROR(500,"验证码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tbUser.getUserId()).claim("userName", tbUser.getUserName()).compact();
        redisTemplate.opsForValue().set("token-"+tbUser.getUserId(),token,60,TimeUnit.MINUTES);
        tbUser.setUserPass(null);
        tbUser.setToken(token);
        return R.OK(tbUser);
    }

    @Override
    public R userReg(UserVo userVo) {

        String key="send-"+userVo.getUserMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if(redisCode==null){
            return R.ERROR(500,"验证码已过期");
        }
        if(!redisCode.equals(userVo.getCode())){
            return R.ERROR(500,"验证码错误");
        }
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, userVo.getUserMobile()));
        if(tbUser!=null){
            return R.ERROR(500,"手机号已存在");
        }

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(userVo.getUserPass());
        System.out.println("加密密码为"+encode);

        tbUser = new TbUser();
        tbUser.setUserName("匿名用户");
        tbUser.setUserMobile(userVo.getUserMobile());
        tbUser.setUserPass(encode);
        tbUser.setCreateBy("系统");
        tbUser.setCreateTime(new Date());
        tbUserMapper.insert(tbUser);
        return R.OK();
    }

    @Override
    public R getTreeMenu() {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
       List<TbMenu> list= tbMenuMapper.getTreeMenu(userId);
        List<Tree<String>> treeList = TreeUtil.build(list, "0", (menu, tree) -> {
            tree.setId(menu.getMenuId() + "");
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid() + "");
            tree.putExtra("path", menu.getMenuPath());
        });
        return R.OK(treeList);
    }

    @Override
    public R getRoleByUserId() {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        TbUser tbUser = tbUserMapper.selectById(userId);
        List<String> roleNames=tbUserMapper.getRoleByUserId(userId);
        StringBuilder stringBuilder = new StringBuilder();
        for (String roleName : roleNames) {
            if(stringBuilder.length()>0){
                stringBuilder.append(",").append(roleName);
            }else {
                stringBuilder.append(roleName);
            }
        }
        tbUser.setRoleNames(stringBuilder.toString());
        return R.OK(tbUser);
    }
}




